package com.lzh.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: liuzhihui
 * @createTime: 2020-06-29 19:56
 **/

@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping(value = "/doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse httpServletResponse) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //把登录成功的用户保存起来
            String token= UUID.randomUUID().toString().replace("-","");
            stringRedisTemplate.opsForValue().set(token,username);

            //把用户的uuid存到浏览器的cookie中
            Cookie sso_token=new Cookie("sso_token",token);
            httpServletResponse.addCookie(sso_token);

            //登录成功，调回原来的页面
            return "redirect:"+url+"?token="+token;
        }
        //登录失败，展示登录页
        return null;
    }
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect") String url, Model model,@CookieValue(value ="sso_token",required = false) String ssoToken){
        if (!StringUtils.isEmpty(ssoToken)){
            return "redirect:"+url+"?token="+ssoToken;
        }

        model.addAttribute("url",url);
        return "login";
    }


}
